package ${genParam.packageName}.${genParam.moduleName}.controller;

import java.util.Arrays;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import ${genParam.packageName}.${genParam.moduleName}.entity.${className};
import ${genParam.packageName}.${genParam.moduleName}.service.${className}Service;
import ${genParam.packageName}.common.utils.PageUtils;
import ${genParam.packageName}.common.utils.R;

<#-- 首字母小写 -->
<#assign uncapJavaName = (className?uncap_first)>
<#assign permizPerfix = genParam.moduleName + ":" +tableName?replace("_", ":")>

/**
 * ${tableDesc}
 *
 * @author gen by king
 * @email xxxx
 * @date ${.now?string["yyyy-MM-dd hh:mm:ss"]}
 */
@RestController
@RequestMapping("${genParam.moduleName}/${tableName?replace("_", "/")}")
@Validated
@Slf4j
public class ${className}Controller {
	
    @Autowired
    private ${className}Service ${uncapJavaName}Service;
    
    <#if extendedFields?? && (extendedFields?size) gt 0 >
    <#list extendedFields as refField>
    @Autowired
    private ${refField.ref.refTable.className}Service ${refField.ref.refTable.className?uncap_first}Service;
    </#list>
    </#if>

    /**
     * 查询${tableDesc}列表
     */
    @GetMapping("/list")
    @RequiresPermissions("${permizPerfix}:list")
    public R list(@RequestParam Map<String, Object> params){
    <#if tableType?? && tableType == 0>
        PageUtils page = ${uncapJavaName}Service.queryPage(params);
        return R.ok().put("page", page);
    <#elseif tableType?? && tableType == 2>
        List<${className}> ${classname}List = ${classname}Service.list();
        if(CollectionUtils.isNotEmpty(goodsCategorys)){
            Map<${pk.attrType},${className}> map = ${classname}List.stream().collect(Collectors.toMap(${className}::get${pk.attrName}, ${classname} -> ${classname}));
            List<${className}> root${className}List = new ArrayList<>();
            for (${className} ${classname} : root${className}List) {
                if(${classname}.getParentId() == -1){
                    root${className}List.add(${classname});
                }else{
                    ${className} children = ${classname};
                    ${className} parent = map.get(children.getParentId());

                    if(CollectionUtils.isEmpty(parent.getChildren())){
                        List<${className}> children${className}List = new ArrayList<>();
                        parent.setChildren(children${className}List);
                    }
                    parent.getChildren().add(children);
                }
            }
            return R.ok().put("treeList",root${className}List);
        }else{
            return R.ok().put("treeList",${classname}List);
        }
    </#if>
    }
	
	<#if !(primaryKeys??) || !primaryKeys?contains(",") >
    /**
     * 根据${primaryKeys}查询 信息
     */
    @GetMapping("/info/{${primaryKeys}}")
    @RequiresPermissions("${permizPerfix}:info")
    public R info(@PathVariable("${primaryKeys}") ${pkType.className} ${primaryKeys}){
		${className} ${uncapJavaName} = ${uncapJavaName}Service.getById(${primaryKeys});
		
		<#--
		<#if extendedFields?? && (extendedFields?size) gt 0 >
	    <#list extendedFields as refField>
	    ${refField.ref.refTableSchema.className} ${refField.ref.refTableSchema.className?uncap_first} = ${refField.ref.refTableSchema.className?uncap_first}Service.getById(${uncapJavaName}.get${primaryKeys?cap_first}());
	    </#list>
	    </#if>
		-->
        return R.ok().put("${uncapJavaName}", ${uncapJavaName});
    }
	</#if>
	
	<#if tableOperates?? && tableOperates?size gt 0>
	<#list tableOperates as operate>
    <#assign  operateName = operate.name?lower_case>
    <#if operateName == "save">
    /**
     * 保存${tableDesc}
     */
    @PostMapping("/save")
    @RequiresPermissions("${permizPerfix}:save")
    public R save(@RequestBody ${className} ${uncapJavaName}){
		${uncapJavaName}Service.save(${uncapJavaName});
        return R.ok();
    }
    <#elseif operateName == "update">

    /**
     * 修改${tableDesc}
     */
    @PostMapping("/update")
    @RequiresPermissions("${permizPerfix}:update")
    public R update(@RequestBody ${className}Entity ${uncapJavaName}){
		${uncapJavaName}Service.updateById(${uncapJavaName});
        return R.ok();
    }
	<#elseif operateName == "del" >
	
    /**
     * 删除${tableDesc}
     */
    @PostMapping("/delete")
    @RequiresPermissions("${permizPerfix}:delete")
    public R delete(@RequestBody ${primaryKeyFieldType.className}[] ${primaryKeys}s){
		${uncapJavaName}Service.removeByIds(Arrays.asList(${primaryKeys}s));
        return R.ok();
    }
<#elseif operateName == "export" >
    /**
     * 导出
     */
    @PostMapping(value = "/export")
    public R exportExcel(${className} ${classname}, HttpServletRequest request, HttpServletResponse response){
        QueryWrapper<${className}> queryWrapper = QueryGenerator.initQueryWrapper(${classname},req.getParameterMap());
        List<${className}> list = ${classname}Service.list(queryWrapper);
        try {
            ExportParams params = new ExportParams();
            params.setType(ExcelType.XSSF);
            params.setStyle(BaseExcelStyle.class);
            Map<String, Object> modelMap = new HashMap<>();
            modelMap.put(NormalExcelConstants.CLASS, ${className}.class);// 导出实体
            modelMap.put(NormalExcelConstants.DATA_LIST, list); // 数据集合
            modelMap.put(NormalExcelConstants.PARAMS, params);// 参数
            String fileName = "${comments}信息_" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
            modelMap.put(NormalExcelConstants.FILE_NAME, URLEncoder.encode(fileName,"UTF-8"));// 文件名称
            response.addHeader("fileName",URLEncoder.encode(fileName,"UTF-8"));
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type","application/vnd.ms-excel");
            response.setHeader("X-Powered-By","Express");
            response.setHeader("Access-Control-Expose-Headers", "fileName");
            PoiBaseView.render(modelMap, request, response,NormalExcelConstants.EASYPOI_EXCEL_VIEW);
            return R.ok("OK");
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("导出出现异常", e);
            }
            return R.error("Error");
        }
    }
<#elseif operateName == "import" >
    /**
     * 导入
     */
    @PostMapping(value = "/import")
    @ResponseBody
    public R importExcel(@NotNull MultipartFile file){
        String fileName = file.getOriginalFilename().toLowerCase();
        if (!fileName.endsWith(".xlsx")) {
            return R.error("不支持的文件格式，仅支持xlsx文件");
        }
        ExcelImportResult<${className}> result = null;
        try {
            ImportParams params = new ImportParams();
            params.setVerifyHandler(${className}Service);
            params.setNeedVerify(true);
            //params.setHeadRows(2);
            result = ExcelImportUtil.importExcelMore(file.getInputStream(), ${className}.class, params);
            //result = new ExcelImportService().importExcelByIs(file.getInputStream(), GoodsExcel.class, params,true);
            if (result.isVerfiyFail()) {
                List<${className}> list = result.getFailList();
                return R.error(JSON.toJSONString(list));
            } else {
                List<${className}> list = result.getList();
                ${className}Service.updateBatchById(list);
            }
        } catch (ExcelImportException e) {
            log.warn("导入的数据格式不正确【是否xxx：填写‘是’或‘否’】", e);
            return R.error(e.getMessage());
        } catch (ServiceException e) {
            log.warn("导入信息异常", e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("导入信息出错：", e);
            return R.error("导入信息出现未知异常");
        }
        return R.ok("OK");
    }
    <#else>
    /**
     * ${(operate.desc)!''}${tableDesc}
     */
    @PostMapping("/${operateName}")
    @RequiresPermissions("${permizPerfix}:${operateName}")
    public R ${operate.name}(@RequestBody ${className} ${uncapJavaName}){
		// ${uncapJavaName}Service.${operateName}(${uncapJavaName}); // TODO
        return R.ok();
    }
	</#if>
    </#list>
    </#if>
}
